require "openssl"
require "base64"
require "digest/sha1"

class UserController < ApplicationController
	SECURITY_KEY = Digest::SHA1.hexdigest("SomeKey")
    
  before_filter :login_required, :only=>['welcome', 'change_password', 'hidden']

  def signup
    @user = User.new(params[:user])
    if request.post?  
      if @user.save
        session[:user] = User.authenticate(@user.login, @user.password)
        flash[:message] = "Signup successful"
				set_cookie( session[:user] )
        redirect_to :action => "welcome"          
      else
        flash[:warning] = "Signup unsuccessful"
      end
    end
  end

  def login
    if request.post?
      if session[:user] = User.authenticate(params[:user][:login], params[:user][:password])
        flash[:message]  = "Login successful"
				set_cookie( session[:user] )
        redirect_to :controller => "home", :action => "index"
      else
        flash[:warning] = "Login unsuccessful"
      end
    end
  end

  def logout
		unset_cookie(session[:user])
    session[:user] = nil
    flash[:message] = 'Logged out'
		redirect_to :controller => "home", :action => "index"
  end

  def forgot_password
    if request.post?
      u= User.find_by_email(params[:user][:email])
      if u and u.send_new_password
        flash[:message]  = "A new password has been sent by email."
        redirect_to :action=>'login'
      else
        flash[:warning]  = "Couldn't send password"
      end
    end
  end
  
  def change_password
    @user=session[:user]
    if request.post?
      @user.update_attributes(:password=>params[:user][:password], :password_confirmation => params[:user][:password_confirmation])
      if @user.save
        flash[:message]="Password Changed"
      end
    end
  end

	def welcome

		id = params[:id]

		redirect_to :action => "login" and return if id.blank?

		cipher = OpenSSL::Cipher::Cipher.new( "des-ecb" )
		cipher.decrypt
		key = session[:salt]
		cipher.key = key
		cipher.iv = SECURITY_KEY

		output = cipher.update( Base64.decode64( CGI.unescape( CGI.unescape( id ) ) ) )
		output << cipher.final
		id = output.to_i
		@user = User.find(id)
	end

private

	def encrypted_id(user)
		# encrypt the user id 
		# see http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/112456
		cipher = OpenSSL::Cipher::Cipher.new( "des-ecb" )
		cipher.encrypt
		key = "#{user.salt}##{SECURITY_KEY}"
		cipher.key = key
		session[:salt] = key
		cipher.iv = SECURITY_KEY
		output = cipher.update( user.id.to_s )
		output << cipher.final
		CGI.escape( CGI.escape( Base64.encode64( output ) ) )
	end

	def set_cookie(user)
		cookies[:id] = { :value => encrypted_id(user), :path => '/', :expires => Time.now + 3600 }
	end

	def unset_cookie(user)
		cookies[:id] = { :value => cookies[:id], :path => '/', :expires => Time.at(0) }
		cookies.delete :id
		logger.debug cookies.size
	end

end
